import React, { useState, useEffect, useRef } from 'react';
import { Table, Space, Button, Popconfirm, message, Pagination } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Axios from "axios";
import * as echarts from 'echarts';

const Index = () => {
  const navigate = useNavigate();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [data, setData] = useState([]); // 表格的数据
  const [searchName, setSearchName] = useState(""); // 查询的name
  const [current, setCurrent] = useState(1); // 当前页
  const [total, setTotal] = useState(0); // 总条数
  const [pageSize, setPageSize] = useState(4); // 界面显示条数
  const searchNameRef = useRef(null);
  const searchAgeRef = useRef(null);
  const searchAddressRef = useRef(null);
  const chartRef = useRef(null); // ECharts 的 DOM 元素引用

  // 饼图数据，包含动态的 total
  const [pieChartData, setPieChartData] = useState([
    { value: 0, name: '总数', label: { formatter: '{b}: {c} ({d}%)' } },
    { value: 2, name: '能耗成本', label: { formatter: '{b}: {c} ({d}%)' } },
    { value: 1, name: '人力成本', label: { formatter: '{b}: {c} ({d}%)' } },
    { value: 2, name: '固定成本', label: { formatter: '{b}: {c} ({d}%)' } },
  ]);

  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 === 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 !== 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
    },
    {
      title: '花费',
      dataIndex: 'cost',
    },
    {
      title: '花费项',
      dataIndex: 'way',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='default' onClick={() => handleEdit(record._id)}>修改</Button>
          <Popconfirm
            title="确认框"
            description="是否确认删除?"
            onConfirm={() => delUser(record._id)}
            onCancel={cancel_del}
            okText="确定"
            cancelText="取消"
            icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
          >
            <Button type='primary' danger>删除</Button>
          </Popconfirm>
          <Button disabled block onClick={() => handleMore(record.key)}>更多</Button>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    GetDataList();
  }, [current]); // 当 current 改变时重新获取数据

  useEffect(() => {
    renderChart();
    return () => {
      if (chartRef.current) {
        echarts.dispose(chartRef.current); // 销毁 ECharts 实例
      }
    };
  }, [pieChartData]); // 当 pieChartData 改变时重新渲染图表

  function GetDataList() {
    Axios.get("http://localhost:3000/finance/list", {
      params: {
        date: searchNameRef.current.value,
        cost: searchAgeRef.current.value,
        way: searchAddressRef.current.value,
        current: current,
        pageSize: pageSize
      }
    }).then((res) => {
      setData(res.data.data);
      setTotal(res.data.count);

      // 更新饼图数据
      setPieChartData([
        { value: res.data.count, name: 'total', label: { formatter: '{b}: {c} ({d}%)' } },
        { value: 3, name: '能耗成本', label: { formatter: '{b}: {c} ({d}%)' } },
        { value: 2, name: '人力成本', label: { formatter: '{b}: {c} ({d}%)' } },
        { value: 1, name: '固定成本', label: { formatter: '{b}: {c} ({d}%)' } },
      ]);
      
      renderChart(); // 更新饼图
    }).catch((err) => {
      console.log("err", err);
    });
  }

  function delUser(_id) {
    Axios.get("http://localhost:3000/finance/del", {
      params: { "_id": _id }
    }).then((res) => {
      if (res.data.code === 0) {
        message.success(res.data.message);
        GetDataList(); // 删除成功后重新获取数据
      } else {
        message.info(res.data.message);
      }
    }).catch((err) => {
      console.log(err);
      message.error("服务器异常");
    });
  }

  function handleEdit(_id) {
    navigate("/home/finance/add?id=" + _id);
  }

  function cancel_del() {
    message.success("取消成功");
  }

  function handleMore(key) {
    // 处理更多操作的逻辑
    console.log("更多操作", key);
  }

  function renderChart() {
    const chartInstance = echarts.init(chartRef.current);
    const option = {
      series: [
        {
          type: 'pie',
          data: pieChartData,
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)' // 格式化显示内容
          }
        },
      ],
    };
    chartInstance.setOption(option);
  }

  function searchList() {
    setCurrent(1); // 查询时重置为第一页
    GetDataList();
  }

  function handleChangePage(num, size) {
    setCurrent(num);
    GetDataList();
  }

  return (
    <>
      <div ref={chartRef} style={{ marginBottom: '20px', width: '100%', height: '300px' }}></div>
      <div style={{ marginBottom: '10px', display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
        <div style={{ marginRight: '10px' }}>
          <input ref={searchNameRef} placeholder="请输入日期" style={{ marginBottom: '10px', padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }} />
        </div>
        <div style={{ marginRight: '10px' }}>
          <input ref={searchAgeRef} placeholder="请输入花费" style={{ marginBottom: '10px', padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }} />
        </div>
        <div style={{ marginRight: '10px' }}>
  <select ref={searchAddressRef} style={{ marginBottom: '10px', padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }}>
    <option value="">请选择花费项目</option>
    <option value="能耗成本">能耗成本</option>
    <option value="人力成本">人力成本</option>
    <option value="固定成本">固定成本</option>
    {/* 添加更多选项 */}
  </select>
</div>
        <Button onClick={searchList} style={{ padding: '16px 16px', borderRadius: '4px', background: '#007bff', color: '#fff', border: 'none' }}>查询</Button>
      </div>
      <Table
        pagination={false}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        style={{ border: '1px solid #ccc', borderRadius: '4px', padding: '10px', boxShadow: '0 0 10px rgba(0,0,0,0.1)' }}
      />
      共 {total} 条数据
      <Pagination total={total} pageSize={pageSize} current={current} onChange={handleChangePage} />
    </>
  );
};

export default Index;